package com.example.springbootsecuritydemo.demos.service;

import com.example.springbootsecuritydemo.demos.entity.SecurityUser;
import com.example.springbootsecuritydemo.demos.mapper.SecurityMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.Objects;

/**
 * @ClassName: MyUserDetailsService
 * @Description:
 * @Date 2024/05/15 09:40
 * @Author songshaoqiu
 **/
@Service
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    SecurityMapper securityMapper;

    @Autowired
    PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SecurityUser allByName = securityMapper.getAllByName(username);
        Assert.notNull(allByName,"用户不存在");
        allByName.setPassword(passwordEncoder.encode(allByName.getPassword()));
        System.out.println("密码:"+allByName.getPassword());
        //{noop} 表示不用加密
        return new User(username, allByName.getPassword(),
                true,
                true,
                true,
                true,
                AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
    }
}
